/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or (at
 * your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 * */

// AmzServer - Tototoy's server model.
// Author: tonyjobmails@gmail.com (tonyhack).
//
// Define class UDPAckOrderPattern.
//
// UDPAckOrderPattern is a simple pattern witch achieves acknowledgement packet just
// like TCP, and this pattern can ensure the packet is ordered.
//

#ifndef __UDP__SOCKET__COMMUNICATOR__H
#define __UDP__SOCKET__COMMUNICATOR__H

#include <map>

#include "common.h"
#include "byte_buffer_static.h"
#include "sort_queue_dynamic_buffer.h"
#include "simple_ring_queue.h"

namespace amz {

namespace udp_ack_order_pattern {

// Acknowledgement sub message.
struct AcknowledgementElement {
  uint8 resend_count_;
  uint32 timestamp_;

  const AcknowledgementElement& operator= (
          const AcknowledgementElement& element) {
    this->resend_count_ = element.resend_count_;
    this->timestamp_ = element.timestamp_;
    return *this;
  }
};

}  // namespace udp_ack_order_pattern

class UDPAckOrderPattern {
 public:
  UDPAckPattern(uint32 max_serial_number, uint8 resend_times, uint32 timeout_msecs);
  virtual ~UDPAckPattern();

  inline bool CheckAdd() const {
    if(count_queue_.Size() >= max_serial_number_)
      return false;
    return true;
  }

  bool Add(const char *data, int size);

  bool AddNewAcknowledgement(const char *data, int size);
  bool GetNextAcknowledgement()

 private:
  uint32 max_serial_number_;
  uint8 resend_times_;
  uint32 timerout_msecs_;
  // Count queue, use to add a serial number to packet
  SimpleRingQueue<uint32> count_queue_;
  // the queue to wait for acknowledge packet.
  SortQueueBufferDynamic<AcknowledgementElement> ack_queue_;
};

}  // namespace amz

#endif  // __UDP__SOCKET__COMMUNICATOR__H
